package com.signcomplex.nettyandroid;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private static final String HOST = "192.168.1.105";
    private static final int PORT = 8090;

    private Handler handler;

    private ProgressDialog progressDialog;

    private EditText accountET;
    private EditText passwordET;
    private Button connectBtn;
    private Button registerBtn;
    private Button loginBtn;

    private ScheduledExecutorService scheduledThreadPool;

    private TimeClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.i("MainActivity-->onCreate");

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        accountET = (EditText) findViewById(R.id.account_edittext);
        passwordET = (EditText) findViewById(R.id.password_edittext);

        connectBtn = (Button) findViewById(R.id.connect_button);
        connectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //显示Progress对话框
                progressDialog = ProgressDialog.show(MainActivity.this, "Tips", "In the connection", true);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            client.init();
                        } catch (Exception e) {
                            e.printStackTrace();
                            LogUtil.i("MainActivity Exception-->" + e.getMessage());
                            if (handler != null) {
                                Message message = new Message();
                                message.what = RequestCode.REQUEST_CODE_ERROR;
                                message.obj = "connection error";
                                handler.sendMessage(message);
                            }
                        }
                    }
                }).start();
            }
        });
        registerBtn = (Button) findViewById(R.id.register_button);
        registerBtn.setOnClickListener(this);
        loginBtn = (Button) findViewById(R.id.login_button);
        loginBtn.setOnClickListener(this);

        registerBtn.setEnabled(false);
        loginBtn.setEnabled(false);

        initBackThread();
    }

    private void initBackThread() {
        scheduledThreadPool = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

        //Handler (com.signcomplex.nettyandroid.MainActivity$5) {334601b2}
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                switch (msg.what) {
                    case RequestCode.REQUEST_CODE_ERROR:
                        connectBtn.setEnabled(true);
                        registerBtn.setEnabled(false);
                        loginBtn.setEnabled(false);
                        break;
                    case RequestCode.REQUEST_CODE_CONNECT:
                        connectBtn.setEnabled(false);
                        registerBtn.setEnabled(true);
                        loginBtn.setEnabled(true);
                        break;
                    case RequestCode.REQUEST_CODE_RECONNECT:
                        if (!progressDialog.isShowing()) {
                            progressDialog.show();
                        }
                        scheduledThreadPool.scheduleAtFixedRate(new Runnable() {

                            @Override
                            public void run() {
                                LogUtil.i("MainActivity-->reconnect");
                                client.doConnect();
                            }
                        }, 1, 5, TimeUnit.SECONDS);
                        break;
                    default:
                        break;
                }
                Toast.makeText(MainActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        client = new TimeClient(PORT, HOST, handler);
    }

    @Override
    public void onClick(View view) {
        String account = accountET.getText().toString().trim();
        String password = passwordET.getText().toString().trim();
        if (account == null || account.length() == 0 || password == null || password.length() == 0) {
            return;
        }
        StringBuffer sb = new StringBuffer("");
        String str = "";
        byte[] req = null;
        switch (view.getId()) {
            case R.id.register_button:
                sb.append(account);
                sb.append(RequestCode.SEPARATOR);
                sb.append(password);

                str = new String(sb);
                LogUtil.i("client send-->" + str);

                try {
                    req = ByteUtil.assembly(str.getBytes(RequestCode.CHARSET_NAME), RequestCode.REQUEST_CODE_REGISTER);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.login_button:
                sb.append(account);
                sb.append(RequestCode.SEPARATOR);
                sb.append(password);

                str = new String(sb);
                LogUtil.i("client send-->" + str);

                try {
                    req = ByteUtil.assembly(str.getBytes(RequestCode.CHARSET_NAME), RequestCode.REQUEST_CODE_LOGIN);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
        }
        if (req != null && TimeClientHandler.getInstance().isConnect()) {
            progressDialog.show();
            ByteBuf firstMessage = Unpooled.buffer(req.length);
            firstMessage.writeBytes(req);
            TimeClientHandler.getInstance().getChannelHandlerContext().writeAndFlush(firstMessage);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        client.close();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
